<template>
  <div id="content" :style="{height:contentHeight+'px'}">
    <Card class="r-n-fs-c">
      <ButtonGroup class="r-n-fs-c">
        <Button @click="showModule = 1" type="primary" style="width: 100px;margin-right:1px;border-right:solid 1px #FFFFFF">任务列表</Button>
        <Button @click="realFlyTask" type="primary" style="width: 100px;">实时飞行</Button>
      </ButtonGroup>
      <Select style="width: 240px;margin-left: 15px;" v-model="page.projectId" @on-change="searchFlyTask" clearable placeholder="所属项目">
        <Option v-for="item in projectList" :key="item.id" :value="item.id">{{item.projectName}}</Option>
      </Select>
      <Select v-if="showModule === 2" style="width: 240px;margin-left: 5px;" clearable placeholder="在线无人机">
        <Option key="all" value="all">所有</Option>
        <Option v-for="item in uavOnlineList" :key="item.id" :value="item.id">{{item.uavName}}</Option>
      </Select>
      <Select v-if="showModule === 2" style="width: 240px;margin-left: 5px;" @on-change="mapSourceSelect" clearable placeholder="地图选择">
        <Option key="ArcGIS" value="ArcGIS">ArcGIS</Option>
        <Option key="TianYu" value="TianYu">天宇地图</Option>
        <Option key="GaoDe" value="GaoDe">高德地图</Option>
      </Select>
      <Select v-if="showModule === 1" style="width: 240px;margin-left: 5px;" v-model="page.flightState" @on-change="searchFlyTask" clearable placeholder="飞行状态">
        <Option :value=0>未飞行</Option>
        <Option :value=1>飞行中</Option>
        <Option :value=2>飞行完毕</Option>
      </Select>
      <Select v-if="showModule === 1" style="width: 240px;margin-left: 5px;" v-model="searchKey" clearable @on-clear="searchKeyClear" placeholder="精确匹配查询参数">
        <Option v-for="item in searchParamList" :key="item.key" :value="item.key">{{item.show}}</Option>
      </Select>
      <Input v-if="showModule === 1" v-model="searchValue" placeholder="请输入查询内容..." clearable style="width: 300px;margin-left: 5px;" />
      <Button v-if="showModule === 1" @click="searchFlyTask" type="primary" style="width: 100px;margin-left: 5px;">查询</Button>
    </Card>
    <Divider/>
    <div v-show="showModule === 1">
      <Table id="card-list-info-table" class="table" stripe
             border
             show-header
             highlight-row
             :loading="isLoading"
             :columns="tableColumns"
             :data="dataList">
      </Table>
      <Divider/>
      <Card style="margin-bottom: 15px;">
        <Page class="r-w-c-c"
              style="width: 100%"
              class-name="card-list-info-page"
              :total="page.total"
              :current="page.pageNum"
              :page-size="page.pageSize"
              @on-change="onPageChange"
              @on-page-size-change="onPageSizeChange"
              show-elevator
              show-sizer
              show-total/>
      </Card>
    </div>
    <div v-show="showModule === 2" id="flyTaskMap" :style="{height:contentHeight-145+'px'}">
      <div class="uav-online-select">
        <div class="uav-online-select-item r-n-fs-c" :style="{background:item['bg']}" v-for="item in uavOnlineSelectList" :key="item.uavId" :value="item.uavId">
          <div class="uav-item-item" style="width: 180px;text-align: center;">{{item.uavName}}</div>
          <div class="uav-item-item" style="width: 240px;text-align: center;">{{item.uavId}}</div>
          <div class="uav-item-item"><span>纬度: </span>{{ item['latitude'] === undefined ? 0.000000 : (item.latitude).toFixed(6)}}</div>
          <div class="uav-item-item"><span>经度: </span>{{item['longitude'] === undefined ? 0.000000 : (item.longitude).toFixed(6)}}</div>
          <div class="uav-item-item"><span>高度: </span>{{item['ultrasonicHeight'] === undefined ? 0.000000 : (item['ultrasonicHeight']).toFixed(6)}}</div>
          <div class="uav-item-item"><span>俯仰: </span>{{(item['pitch'] === undefined ? 0.000000 : item['pitch']).toFixed(6)}}</div>
          <div class="uav-item-item"><span>横滚: </span>{{(item['roll'] === undefined ? 0.000000 : item['roll']).toFixed(6)}}</div>
          <div class="uav-item-item"><span>偏航: </span>{{(item['yaw'] === undefined ? 0.000000 : item['yaw']).toFixed(6)}}</div>
          <div class="iconfont icon-dingwei uav-btn" :style="{background:item['bg']}" style="right: -29px;" @click="setMapUavCenter(item.uavId)"></div>
          <div class="iconfont icon-zhiboyun uav-btn" :style="{background:item['bg']}" style="right: -58px;" @click="startUavLiveVideo(item.uavId)"></div>
        </div>
      </div>
    </div>
    <Modal v-model="modalTip" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>操作确认</span>
      </p>
      <div style="text-align:center">
        <p>{{ modalTipContent }}</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="modalLoading" @click="modalTipOk">确认操作</Button>
      </div>
    </Modal>
    <Modal v-model="isMessageUpdateModalShow" :title="modalTitle">
      <Form ref="ruleValidate" :rules="ruleValidate" :model="operateForm"
            style="margin-left: 0;width: 100%;">
        <div class="r-n-fs-c item-input">
          <label class="item-input-span">飞行状态</label>
          <Select v-model="operateForm.flightState" clearable placeholder="飞行状态">
            <Option :value=1 >飞行中</Option>
            <Option :value=2 >飞行结束</Option>
          </Select>
        </div>
        <div class="r-n-fs-c item-input">
          <label class="item-input-span">飞行人员</label>
          <Select v-model="operateForm.userId" clearable placeholder = "飞行人员">
            <Option v-for="item in userList" :key="item.id" :value=item.id >{{item.nickName}}</Option>
          </Select>
        </div>
        <div class="r-n-fs-c item-input">
          <label class="item-input-span">所属管线</label>
          <Select v-model="operateForm.pipelineId" clearable placeholder = "所属管线">
            <Option v-for="item in pipelineList" :key="item.id" :value=item.id >{{item.name}}</Option>
          </Select>
        </div>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">任务名称</span>
          <FormItem prop="taskName">
            <Input placeholder="任务名称" v-model="operateForm.taskName"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">开始时间</span>
          <FormItem>
            <Input placeholder="开始时间" disabled v-model="operateForm.startTime"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">结束时间</span>
          <FormItem>
            <Input placeholder="结束时间" disabled v-model="operateForm.endTime"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">飞行距离</span>
          <FormItem>
            <Input placeholder="飞行距离" disabled v-model="operateForm.flightDistance"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">飞行时长</span>
          <FormItem>
            <Input placeholder="飞行时长" disabled v-model="operateForm.flightDuration"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">飞行视频</span>
          <FormItem>
            <Input placeholder="无" disabled v-model="operateForm.videoUrl"/>
          </FormItem>
        </label>

      </Form>
      <div slot="footer">
        <Button type="default" @click="isMessageUpdateModalShow=false">取消</Button>
        <Button type="primary" @click="getTaskMessageFromPlatForm()">获取平台任务信息</Button>
        <Button type="primary" @click="modalOk()">提交信息</Button>
      </div>
    </Modal>
    <Modal v-model="isFlyTaskTrackModalShow" footer-hide width="1000" :title="modalTitle">
      <div style="width: 100%;max-height: 500px;">
        <div id="flyTaskTrackMap" style="width: inherit;min-height: 500px"></div>
      </div>
    </Modal>

    <Modal v-model="isFlyTaskTrackDownloadModalShow" width="350" footer-hide title="航迹下载格式">
      <Button type="default" style="width: 100px;margin-left: 5px;" @click="trackDownload(1)">源ProtoBuf</Button>
      <Button type="default" style="width: 100px;margin-left: 5px;" @click="trackDownload(2)">JSON文件</Button>
      <Button type="default" style="width: 100px;margin-left: 5px;" @click="trackDownload(3)">日志文件</Button>
    </Modal>
  </div>
</template>

<script>

import {mapGetters, mapState} from "vuex"
import axios from "axios";
import {LeafLetMap} from "@/global/mapConfig";
import moment from "moment";
import {host, mapUrl,Request} from "@/global/config";
import _ from "lodash";
import {Data} from "@/global/webSocket.js";
import {DataList} from "@/global/webSocket.js";
import store from "@/store";
import phantom from "phantom";
import webpage from "webpage";


export default {
  name: "FlyTask",
  computed: {
    ...mapState(["url", "host", "resourceHost","onlineUavMap","realSideWidth","projectList"]),
    ...mapGetters(["contentWidth", "contentHeight"]),
  },
  data() {
    return {
      isFlyTaskTrackModalShow: false,
      isFlyTaskTrackDownloadModalShow: false,
      isMessageUpdateModalShow: false,
      searchKey: null,
      showModule: 1,
      searchValue: null,
      btnLoading: false,
      isLoading: false,
      modalTip: false,
      modalTipContent: null,
      modalLoading: false,
      isFileAnalyseModalShow: false,
      isPageSizeChanging: false,
      modalTitle: '任务编辑',
      modalTitleData: null,
      operatorType: ['任务编辑','任务禁用','任务解禁','任务删除'],
      headers: {
        'u-projectId': null,
        'u-uid': null,
        'u-token': null,
      },
      operateForm:{
        id: null,
        taskSource: null,
        taskNumber: null,
        taskName: null,
        telemetryUrl: null,
        flightState: null,
        startTime: null,
        endTime: null,
        flightDuration: null,
        flightDistance: null,
        videoUrl: null,
        userId: null,
        pipelineId: null,
        projectId: null
      },
      ruleValidate: {
        taskName: [
          {required: true, type: 'string', message: '任务名称不能为空',trigger: 'blur'},
          {min: 2, message: '版本号不能少于2个字符', trigger: 'change'},
          {max: 20, message: '版本号不能超过20个字符', trigger: 'change'}
        ]
      },
      selectForm: {
        id: null,
        taskNumber: null,
        taskName: null,
        uavId: null,
        uavName: null,
        startTime: null,
        endTime: null,
        flightState: null,
        userId: null,
        state: null,
        projectId: null
      },
      page:{
        total: 0,
        pageSize: 10,
        pageNum: 1,
        descParams:'id',
        id: null,
        taskNumber: null,
        taskName: null,
        uavId: null,
        uavName: null,
        flightState: null,
        userId: null,
        startTime: null,
        endTime: null
      },
      tableColumns: [
        {
          title: '任务ID',
          key: 'id',
          width: 100,
          minWidth: 100,
          resizable: true,
          align: "center",
          ellipsis: true,
          sortable: true,
        },
        {
          title: '任务来源',
          key: 'taskSource',
          resizable: true,
          minWidth: 100,
          align: "center",
          fixed: "left",
          render: function (createElement, data) {
            let {taskSource} = data.row;
            let sourceMap = {
              1 : '云平台',
              2 : '御空'
            }
            return createElement('span',sourceMap[taskSource]);
          }
        },
        {
          title: '任务编号',
          key: 'taskNumber',
          resizable: true,
          minWidth: 100,
          align: "center",
          fixed: "left"
        },
        {
          title: '任务名称',
          key: 'taskName',
          resizable: true,
          width: 150,
          minWidth: 100,
          align: "center",
        },
        {
          title: '无人机ID',
          key: 'uavId',
          resizable: true,
          width: 180,
          minWidth: 150,
          align: "center"
        },
        {
          title: '无人机名称',
          key: 'uavName',
          resizable: true,
          minWidth: 150,
          align: "center"
        },
        {
          title: '飞行状态',
          key: 'flightState',
          resizable: true,
          width: 130,
          align: "center",
          render: function(createElement, data) {
            let {flightState} = data.row;
            if (flightState === 0) {
              return createElement('Tooltip',{
                attrs: {
                  content :"未飞行",
                  placement : "top",
                  transfer: true
                }
              },[createElement('div',{
                style: {
                  height:'15px',
                  width:'15px',
                  borderRadius:'50%',
                  background: '#b57373'
                }
              },'')]);
            }
            if (flightState === 1) {
              return createElement('Tooltip',{
                attrs: {
                  content :"飞行中",
                  placement : "top",
                  transfer: true
                }
              },[createElement('div',{
                style: {
                  height:'15px',
                  width:'15px',
                  borderRadius:'50%',
                  background: '#1afa29'
                }
              },'')]);
            }
            if (flightState === 2) {
              return createElement('Tooltip',{
                attrs: {
                  content :"飞行完毕",
                  placement : "top",
                  transfer: true
                }
              },[createElement('div',{
                style: {
                  height:'15px',
                  width:'15px',
                  borderRadius:'50%',
                  background: '#838383'
                }
              },'')]);
            }
          },
        },
        {
          title: '开始时间',
          key: 'startTime',
          resizable: true,
          minWidth: 180,
          align: "center",
          render: function (createElement, data) {
            let {startTime} = data.row;
            if (startTime === null || startTime === undefined){
              return createElement('span','-')
            }
            return createElement('span',moment.unix(startTime/1000).format('YYYY-MM-DD HH:mm:ss'));
          }
        },
        {
          title: '结束时间',
          key: 'endTime',
          resizable: true,
          width: 180,
          align: "center",
          render: function (createElement, data) {
            let {endTime} = data.row;
            if (endTime === null || endTime === undefined){
              return createElement('span','-')
            }
            return createElement('span',moment.unix(endTime/1000).format('YYYY-MM-DD HH:mm:ss'));
          }
        },
        {
          title: '飞行时间',
          key: 'flightDuration',
          resizable: true,
          width: 150,
          align: "center",
          render: this.flightDurationRender
        },
        {
          title: '飞行距离',
          key: 'flightDistance',
          resizable: true,
          width: 130,
          align: "center",
          render: function (createElement,data){
            let {flightDistance} = data.row;
            return createElement('span',flightDistance + "米")
          }
        },
        {
          title: '遥测',
          key: 'telemetryUrl',
          resizable: true,
          width: 130,
          align: "center",
          render: function (createElement,data){
            let {telemetryUrl} = data.row;
            if (telemetryUrl === null || telemetryUrl === undefined){
              return createElement('span','-');
            }
            return createElement('Tooltip',{
              attrs: {
                content : telemetryUrl,
                placement : "top-start",
                style: {
                  width: '100%'
                },
                transfer: true
              }
            },[createElement('div',telemetryUrl.substring(telemetryUrl.lastIndexOf("/")+1))]);
          }
        },
        {
          title: '视频',
          key: 'videoUrl',
          resizable: true,
          width: 200,
          align: "center",
          render: function (createElement,data){
            let {videoUrl} = data.row;
            if (videoUrl === null || videoUrl === undefined){
              return createElement('span','-');
            }
            return createElement('Tooltip',{
              attrs: {
                content : videoUrl,
                placement : "top-start",
                maxWidth: '300px',
                transfer: true
              }
            },[createElement('div',videoUrl.substring(videoUrl.lastIndexOf("/")+1))]);
          }
        },
        {
          title: '所属管线',
          key: 'pipelineId',
          resizable: true,
          width: 130,
          align: "center",
          render: function (createElement,data){
            let {pipelineId} = data.row;
            if (pipelineId === null || pipelineId === undefined){
              return createElement('span','-');
            }
            return createElement('Tooltip',{
              attrs: {
                content : pipelineId,
                placement : "top-start",
                style: {
                  width: '100%'
                },
                transfer: true
              }
            },[createElement('div',pipelineId)]);
          }
        },
        {
          title: '飞行人员',
          key: 'userId',
          resizable: true,
          width: 130,
          align: "center",
          render: function (createElement,data){
            let {userId} = data.row;
            if (userId === null || userId === undefined){
              return createElement('span','-');
            }
            return createElement('Tooltip',{
              attrs: {
                content : userId,
                placement : "top-start",
                style: {
                  width: '100%'
                },
                transfer: true
              }
            },[createElement('div',userId)]);
          }
        },
        {
          title: '险情数量',
          key: 'dangerCount',
          resizable: true,
          width: 130,
          align: "center"
        },
        {
          title: '所属项目',
          key: 'projectId',
          resizable: true,
          width: 200,
          align: "center",
          fixed: "left",
          render: Request.projectNameRender
        },
        {
          title: '操作',
          resizable: true,
          minWidth: 600,
          align: "center",
          fixed: "right",
          render: this.operatorRenderFunction
        }
      ],
      dataList: [],
      pipelineList: [],
      userList: [],
      uavOnlineList: [],
      searchParamList: [
        {
          key: "id",
          show: "任务ID",
        },
        {
          key: "taskNumber",
          show: "任务编号",
        },
        {
          key: "taskName",
          show: "任务名称(模糊匹配)",
        },
        {
          key: "uavId",
          show: "无人机ID",
        },
        {
          key: "uavName",
          show: "无人机名称",
        },
        {
          key: "userId",
          show: "飞手ID",
        }
      ],
      flyTaskMap: null,
      uavPopupMap: new Map(),
      uavOnlineSelectList: [],
      currentUav: null,
      flyTaskTrackMap: null,
      flyTaskTrackPolyline: null,
    }
  },
  watch: {
    onlineUavMap:function (e){
      if (this.flyTaskMap !== null){
        e.forEach((telemetry,uavId)=>{
          let self = this;
          let index = self.uavOnlineSelectList.findIndex(value => value.uavId === uavId);
          if (telemetry['longitude'] === undefined){
            telemetry['longitude'] = 0;
          }
          if (telemetry['latitude'] === undefined){
            telemetry['latitude'] = 0;
          }
          if (self.currentUav !== null && telemetry.uavId === self.currentUav.uavId){
            telemetry['bg'] = '#FF6700';
            self.flyTaskMap.map.setView([telemetry['latitude'],telemetry['longitude']],self.flyTaskMap.map.getZoom());
          }else {
            telemetry['bg'] = '#0008';
          }
          if (index !== -1){
            self.uavOnlineSelectList.splice(index,1,telemetry);
          }else {
            self.uavOnlineSelectList.push(telemetry);
          }
          let key = `div[data-uavId-`+telemetry['uavId']+']';
          let selector = document.querySelector(key);
          if (selector !== null){
            self.flyTaskMap.removeLayer(self.uavPopupMap.get(uavId));
            let popup = self.flyTaskMap.addUavPopup(telemetry,false,(e)=>{});
            self.uavPopupMap.set(uavId,popup);
          }else {
            let popup = self.flyTaskMap.addUavPopup(telemetry,false,(e)=>{});
            self.uavPopupMap.set(uavId,popup);
          }
        })
      }
    }
  },
  created: function () {
  },
  mounted: function () {
    let self = this;
    this.selectPageList(this.page);
  },
  methods: {
    searchFlyTask(){
      this.page.pageNum = 1;
      this.selectPageList(this.page);
    },
    getTaskMessageFromPlatForm(){
      this.platformTaskFetch(this.operateForm);
    },
    modalOk(){
      let isValidate = false;
      this.$refs['ruleValidate'].validate((valid) => {
        if (valid) {
          isValidate = true;
        }
      });
      if (!isValidate) {
        return;
      }
      this.updateFlyTask(this.operateForm);
    },
    setMapUavCenter(uavId){
      let telemetry = this.onlineUavMap.get(uavId);
      if (telemetry['latitude'] === null){
        telemetry['latitude'] = 0;
      }
      if (telemetry['longitude'] === null){
        telemetry['longitude'] = 0;
      }
      this.flyTaskMap.map.setView([telemetry['latitude'],telemetry['longitude']],this.flyTaskMap.map.getZoom());
      if (this.currentUav === null){
        this.currentUav = telemetry;
      }
      else if (telemetry.uavId === this.currentUav.uavId) {
        this.currentUav = null;
      }else {
        let curIndex = this.uavOnlineSelectList.findIndex((value => value.uavId === this.currentUav.uavId));
        if (curIndex !== -1){
          this.uavOnlineSelectList[curIndex].bg = '#0008';
        }
        this.currentUav = telemetry;
      }
      let findIndex = this.uavOnlineSelectList.findIndex((value => value.uavId === uavId));
      if (findIndex !== -1){
        this.uavOnlineSelectList[findIndex].bg = '#FF6700';
      }else {
        this.uavOnlineSelectList[findIndex].bg = '#0008';
      }
    },
    startUavLiveVideo(uavId){
      let telemetry = this.onlineUavMap.get(uavId);
      let source = telemetry.source;
      if (source === '云平台'){
        console.log(telemetry.uavId)
      }
      if (source === '御空'){
        console.log(telemetry['taskId'])
      }
    },
    searchKeyClear(){
      let self = this;
      self.searchValue = null;
    },
    realFlyTask(){
      this.showModule = 2;
      if (this.flyTaskMap === null){
        if (localStorage.getItem('mapSource') === null){
          localStorage.setItem('mapSource','ArcGIS');
        }
        setTimeout(()=>{this.flyTaskMap = new LeafLetMap(document.getElementById("flyTaskMap"),mapUrl[localStorage.getItem('mapSource')]);},10);
      }
    },
    mapSourceSelect(mapSource){
      localStorage.setItem('mapSource',mapSource);
      this.flyTaskMap.remove();
      this.flyTaskMap = new LeafLetMap(document.getElementById("flyTaskMap"),mapUrl[mapSource]);
    },
    flightDurationRender(createElement,data){
      let self = this;
      let {flightDuration} = data.row;
      return createElement('span',self.timeUnitConversion(flightDuration,0));
    },
    timeUnitConversion(number,decimalPoint=0){
      let conversionFlow = 0;
      if(60 > number){
        conversionFlow = parseInt(number)+"秒";
      }else if(60 < number && number < (60 * 60)){
        conversionFlow = (number/60).toFixed(decimalPoint)+"分钟";
      }else if(number > (60 * 60)) {
        conversionFlow = (number/(60*60)).toFixed(decimalPoint)+"小时";
      }
      return conversionFlow;
    },
    onPageChange(changedPage) {
      this.page.pageNum = changedPage;
      !this.isPageSizeChanging ? this.selectPageList(this.page) : {};
    },
    onPageSizeChange(changedPageSize) {
      this.isPageSizeChanging = true;
      new Promise(resolve => {
        this.page.pageSize = changedPageSize;
        resolve(changedPageSize)
      }).then(() => {
        this.selectPageList(this.page);
        this.isPageSizeChanging = false;
      })
    },
    modalTipOk() {
      this.modalLoading = true;
      switch (this.modalTitle){
        case this.operatorType[1]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.disableFlyTask(this.operateForm.id);
        }break;
        case this.operatorType[2]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.enableFlyTask(this.operateForm.id, this.operateForm.projectId);
        }break;
        case this.operatorType[3]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.deleteFlyTask(this.operateForm.id);
        }break;
      }
    },
    operatorRenderFunction(createElement, data) {
      let self = this;
      let {
        id,taskNumber,taskName,uavId,uavName,taskSource,flightDistance,flightDuration,startTime,endTime,flightState,telemetryUrl,videoUrl,userId,dangerCount,pipelineId,state,projectId
      } = data.row;
      let btnList = [];

      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: '#5cadff'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            self.downloadFlyTaskReport(id,taskName);
          }
        },
      }, "报告下载"));

      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: telemetryUrl !== undefined ? '#5cadff': '#00000030'
        },
        attrs: {
          type: "dashed",
          disabled: telemetryUrl === undefined,
        },
        nativeOn: {
          click: function () {
            self.operateForm.telemetryUrl = telemetryUrl;
            self.operateForm.taskName = taskName;
            self.isFlyTaskTrackDownloadModalShow = true;
          }
        },
      }, "航迹下载"));

      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: telemetryUrl !== undefined ? '#5cadff': '#00000030'
        },
        attrs: {
          disabled: telemetryUrl === undefined,
          type: "dashed"
        },
        nativeOn: {
          click: function () {
                self.showFlyTaskTrackMap(telemetryUrl,data.row);
          }
        },
      }, "航迹展示"));

      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '80px',
          border: '#5CADFF 1px dashed',
          color: '#5cadff'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            axios.all([self.selectUserList(projectId), self.selectPipelineList(projectId)]).then(self.axios.spread(function (response1, response2) {
              if (response1.data.state === 200) {
                let {records} = response1.data.content;
                self.userList = records;
              } else {
                self.$Message.error('用户列表获取失败...');
              }

              if (response2.data.state === 200) {
                let {records} = response2.data.content;
                self.pipelineList = records;
              } else {
                self.$Message.error('管线列表获取失败...');
              }

              self.operateForm.id = id;
              self.operateForm.taskName = taskName;
              self.operateForm.startTime = startTime;
              self.operateForm.endTime = endTime;
              self.operateForm.taskNumber = taskNumber;
              self.operateForm.taskSource = taskSource;
              self.operateForm.flightState = flightState;
              self.operateForm.flightDistance = flightDistance;
              self.operateForm.flightDuration = flightDuration;
              self.operateForm.videoUrl = videoUrl;
              self.operateForm.userId = userId;
              self.operateForm.pipelineId = pipelineId;
              self.operateForm.projectId = projectId;
              self.isMessageUpdateModalShow = true;
            }))

          }
        },
      }, '编辑'));

      if (state === 0){
        btnList.push(createElement('Button', {
          'class': 'button-item',
          style: {
            width: '80px',
            border: '#5CADFF 1px dashed',
            color: '#FF6666'
          },
          attrs: {
            type: "dashed"
          },
          nativeOn: {
            click: function () {
              self.operateForm.projectId = projectId;
              self.operateForm.id = id;
              self.modalTipContent = "将要禁用项目["+projectId + "] 的飞行任务["+id+"] "+taskName+", 是否继续? ";
              self.modalTitle = self.operatorType[1];
              self.modalTip = true;
            }
          },
        }, "禁用"));
      }else if (state === 1) {
        btnList.push(createElement('Button', {
          'class': 'button-item',
          style: {
            width: '80px',
            border: '#5CADFF 1px dashed',
            color: '#5cadff'
          },
          attrs: {
            type: "dashed"
          },
          nativeOn: {
            click: function () {
              self.operateForm.projectId = projectId;
              self.operateForm.id = id;
              self.modalTipContent = "将要解禁项目["+projectId + "] 的飞行任务["+id+"] "+taskName+", 是否继续? ";
              self.modalTitle = self.operatorType[2];
              self.modalTip = true;
            }
          },
        }, "解禁"));
      }
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '80px',
          border: '#5CADFF 1px dashed',
          color: '#FF6666'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            if (dangerCount > 0){
              self.$Message.info("该任务存在绑定险情");
            }
            self.operateForm.projectId = projectId;
            self.operateForm.id = id;
            self.modalTipContent = "将要删除项目["+projectId + "] 的飞行任务["+id+"] "+taskName+", 是否继续? ";
            self.modalTitle = self.operatorType[3];
            self.modalTip = true;
          }
        },
      }, "删除"));
      return createElement("div", {'class': 'r-n-c-c'}, [
        createElement('ButtonGroup', btnList),
      ])
    },
    trackDownload(outputType){
      let self = this;
      self.isFlyTaskTrackDownloadModalShow = false;
      if (self.operateForm.telemetryUrl !== undefined){
        self.downloadFlyTaskTrackFile(self.operateForm.telemetryUrl,self.operateForm.taskName,outputType);
      }else {
        self.$Message.error("该任务航迹未存储!");
      }
    },
    showFlyTaskTrackMap(telemetryUrl,flyTask){
      let self = this;
      axios.get(telemetryUrl,{
        transformRequest: [function (data, headers) {
          delete headers.common["u-token"];
          delete headers.common["u-uid"];
          delete headers.common["u-projectId"];
          return data;
        }],
        responseType: 'blob'
      }).then(function (response) {
        let blob = new Blob([response.data]);
        blob.arrayBuffer().then((buffer)=>{
          let array = new Uint8Array(buffer);
          let message = DataList.decode(array);
          let dataList = message.toJSON();
          self.renderFlyTaskTrack(dataList, self, flyTask);
        })
      });
    },
    renderFlyTaskTrack(dataList, self, flyTask) {
      let points = [];
      for (let point of dataList['data']) {
        if (point['latitude'] !== undefined && point['longitude'] !== undefined) {
          points.push({lat: point.latitude, lng: point.longitude});
        }
      }
      if (self.flyTaskTrackPolyline !== null) {
        self.flyTaskTrackMap.removeLayer(self.flyTaskTrackPolyline);
      }
      if (points.length > 0){
        let source;
        if (flyTask.taskSource === 1){
          source = "云平台";
        }else if (flyTask.taskSource === 2) {
          source = "御空";
        }else {
          source = "";
        }
        self.modalTitle = source + "任务[" + flyTask.taskNumber + "] - 遥测总计["+points.length+"]";
        this.doRenderFlyTaskTrack(points);
      }else {
        self.$Message.error("航迹经纬度缺失...")
      }
    },
    doRenderFlyTaskTrack(points){
      let self = this;
      self.isFlyTaskTrackModalShow = true;
      if (self.flyTaskTrackMap === null){
        if (localStorage.getItem('mapSource') === null){
          localStorage.setItem('mapSource','ArcGIS');
        }
        setTimeout(()=>{
          self.flyTaskTrackMap = new LeafLetMap(document.getElementById("flyTaskTrackMap"),mapUrl[localStorage.getItem('mapSource')]);
          self.flyTaskTrackPolyline = self.flyTaskTrackMap.renderInspectLine(points, {
            type: 'line',
            color: '#FF6700',
            opacity: 0.7,
            weight: 4
          });
        },10);
      }else {
        self.flyTaskTrackPolyline = self.flyTaskTrackMap.renderInspectLine(points, {
          type: 'line',
          color: '#FF6700',
          opacity: 0.7,
          weight: 4
        });
      }
    },
    downloadFlyTaskTrackFile(url,fileName,outputType){
      let self = this;
      axios.get(url,{
        transformRequest: [function (data, headers) {
          delete headers.common["u-token"];
          delete headers.common["u-uid"];
          delete headers.common["u-projectId"];
          return data;
        }],
        responseType: 'blob'
      }).then(function (response) {
        let blob = new Blob([response.data]);
        if (outputType === 1){
          self.download(fileName + '.pb',blob);
        }
        if (outputType === 2){
          blob.arrayBuffer().then((buffer)=>{
            let array = new Uint8Array(buffer);
            let message = DataList.decode(array);
            let dataList = message.toJSON();
            let jsonStringBlob = new Blob([JSON.stringify(dataList,(data,value)=>{
              if (typeof value === "number"){
                return Number.parseFloat(value.toFixed(6));
              }
              return value},4)]);
            self.download(fileName + '.json',jsonStringBlob);
          })
        }
        //飞行日志
        if (outputType === 3){
          blob.arrayBuffer().then((buffer)=>{
            let array = new Uint8Array(buffer);
            let message = DataList.decode(array);
            let dataList = message.toJSON();
            let logBuffer = "";
            logBuffer += "任务编号:\t"+dataList['taskId'] + '\n';
            if (dataList['uavName'] !== undefined || dataList['uavId'] !== undefined){
              logBuffer += dataList['uavName'] !== undefined ? "执行飞机:\t"+dataList['uavName'] + '\n':"执行飞机:\t"+dataList['uavId'] + '\n';
            }else {
              logBuffer += "执行飞机:\t未知\n";
            }
            logBuffer += "任务来源:\t"+dataList['source'] + '\n';
            logBuffer += "项目ID:\t"+dataList['projectId'] + '\n';
            logBuffer += "开始时间:\t"+moment.unix(dataList['startTime']/1000).format('YYYY-MM-DD HH:mm:ss') + '\n';
            logBuffer += "结束时间:\t"+moment.unix(dataList['endTime']/1000).format('YYYY-MM-DD HH:mm:ss') + '\n';
            for (let telemetry of dataList['data']) {
              logBuffer += `${moment.unix(telemetry['timestamps']/1000).format('YYYY-MM-DD HH:mm:ss')} `;
              telemetry['latitude'] !== undefined ? logBuffer += `纬度[${telemetry['latitude'].toFixed(6)}] `:'';
              telemetry['longitude'] !== undefined ? logBuffer += `经度[${telemetry['longitude'].toFixed(6)}] `:'';
              telemetry['ultrasonicHeight'] !== undefined ? logBuffer += `相对高度[${telemetry['ultrasonicHeight'].toFixed(6)}] `:'';
              telemetry['altitudeHeight'] !== undefined ? logBuffer += `海拔高度[${telemetry['altitudeHeight'].toFixed(6)}] `:'';
              telemetry['airspeed'] !== undefined ? logBuffer += `空速[${telemetry['airspeed'].toFixed(6)}] `:'';
              telemetry['velocity'] !== undefined ? logBuffer += `地速[${telemetry['velocity'].toFixed(6)}] `:'';
              telemetry['yaw'] !== undefined ? logBuffer += `偏航[${telemetry['yaw'].toFixed(6)}] `:'';
              telemetry['roll'] !== undefined ? logBuffer += `横滚[${telemetry['roll'].toFixed(6)}] `:'';
              telemetry['pitch'] !== undefined ? logBuffer += `俯仰[${telemetry['pitch'].toFixed(6)}] `:'';
              telemetry['ptYaw'] !== undefined ? logBuffer += `载荷偏航[${telemetry['ptYaw'].toFixed(6)}] `:'';
              telemetry['ptRoll'] !== undefined ? logBuffer += `载荷横滚[${telemetry['ptRoll'].toFixed(6)}] `:'';
              telemetry['ptPatch'] !== undefined ? logBuffer += `载荷俯仰[${telemetry['ptPatch'].toFixed(6)}] `:'';
              logBuffer += `\n`;
            }
            let logStringBlob = new Blob([logBuffer]);
            self.download(fileName + '.txt',logStringBlob);
          })
        }
      });
    },
    download(outputFileName,blob){
      if (outputFileName === undefined || outputFileName === null){
        this.$Message.error("文件名称为空...")
        return;
      }
      let eleLink = document.createElement('a')
      eleLink.download = outputFileName;
      eleLink.style.display = 'none'
      eleLink.href = window.URL.createObjectURL(blob)
      document.body.appendChild(eleLink)
      eleLink.click()
      document.body.removeChild(eleLink)
    },
    downloadFlyTaskReport(flyTaskId,taskName){
      axios.get(this.url.fly_task_report + flyTaskId,{
        responseType: 'blob'
      }).then(function (response) {
        let blob = new Blob([response.data]);
        let eleLink = document.createElement('a')
        eleLink.download = taskName + '.pdf'
        eleLink.style.display = 'none'
        eleLink.href = window.URL.createObjectURL(blob)
        document.body.appendChild(eleLink)
        eleLink.click()
        document.body.removeChild(eleLink)
      });
    },
    selectPageList(selectForm) {
      let self = this;
      let form = Object.assign({}, selectForm);
      if (self.searchKey !== null && self.searchValue !== null && self.searchValue !== ""){
        form[self.searchKey] = self.searchValue.trim();
      }
      self.isLoading = true;
      axios.get(self.url.fly_task_list, {params: form}).then(function (response) {
        let {records,total} = response.data.content;
        self.page.total = total;
        self.dataList = records;
        self.isLoading = false;
      }).catch(function () {
        self.isLoading = false;
      });
    },
    disableFlyTask(flyTaskId){
      let self = this;
      axios.delete(self.url.fly_task_delete2 + flyTaskId).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.$Message.success(message);
          self.selectPageList(self.page);
          self.$Spin.hide();
        }
      })
    },
    enableFlyTask(flyTaskId,projectId){
      let self = this,form = {};
      form['projectId'] = projectId;
      form['id'] = flyTaskId;
      form['state'] = 0;
      axios.patch(self.url.fly_task_modify, form).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.$Message.success(message);
          self.selectPageList(self.page);
          self.$Spin.hide();
        }
      })
    },
    deleteFlyTask(flyTaskId){
      let self = this;
      axios.delete(self.url.fly_task_delete + flyTaskId).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.$Message.success(message);
          if (self.page.total === (self.page.pageNum - 1) * self.page.pageSize + 1 ){
            self.page.pageNum--;
          }
          self.selectPageList(self.page);
          self.$Spin.hide();
        }
      })
    },
    updateFlyTask(selectForm){
      let self = this,form = {};
      selectForm['projectId'] !== undefined ? form['projectId'] = selectForm['projectId']:{};
      selectForm['taskSource'] !== undefined ? form['taskSource'] = selectForm['taskSource']:{};
      selectForm['id'] !== undefined ? form['id'] = selectForm['id']:{};
      selectForm['taskNumber'] !== undefined ? form['taskNumber'] = selectForm['taskNumber']:{};

      selectForm['taskName'] !== undefined ? form['taskName'] = selectForm['taskName']:{};
      selectForm['flightState'] !== undefined ? form['flightState'] = selectForm['flightState']:{};
      selectForm['flightDistance'] !== undefined ? form['flightDistance'] = selectForm['flightDistance']:{};
      selectForm['flightDuration'] !== undefined ? form['flightDuration'] = selectForm['flightDuration']:{};
      selectForm['startTime'] !== undefined ? form['startTime'] = selectForm['startTime']:{};
      selectForm['endTime'] !== undefined ? form['endTime'] = selectForm['endTime']:{};
      selectForm['videoUrl'] !== undefined ? form['videoUrl'] = selectForm['videoUrl']:{};
      selectForm['pipelineId'] !== undefined ? form['pipelineId'] = selectForm['pipelineId']:{};
      selectForm['userId'] !== undefined ? form['userId'] = selectForm['userId']:{};
      selectForm['telemetryUrl'] !== undefined ? form['telemetryUrl'] = selectForm['telemetryUrl']:{};

      axios.patch(self.url.fly_task_modify, form).then(function (response) {
        let {message, state,content} = response.data;
        if (state === 200) {
          self.$Message.success(message);
          self.isMessageUpdateModalShow = false;
          self.selectPageList(self.page);
          self.$refs['ruleValidate'].resetFields();
          self.$Spin.hide();
        }else {
          if (content === 'taskName'){
            self.$Message.error("任务名称非法")
          }
        }
      })
    },
    selectPipelineList(projectId) {
      let self = this;
      let form = {};
      form['projectId'] = projectId;
      return axios.get(self.url.pipeline_list, {params: form});
    },
    selectUserList(projectId) {
      let self = this;
      let form = {};
      form['projectId'] = projectId;
      form['roleId'] = 5;
      return axios.get(self.url.user_list, {params: form});
    },
    platformTaskFetch(selectForm){
      let self = this,form = {};
      selectForm['id'] !== undefined ? form['id'] = selectForm['id']:{};
      selectForm['taskNumber'] !== undefined ? form['taskNumber'] = selectForm['taskNumber']:{};
      selectForm['taskSource'] !== undefined ? form['taskSource'] = selectForm['taskSource']:{};
      selectForm['projectId'] !== undefined ? form['projectId'] = selectForm['projectId']:{};
      axios.post(self.url.fly_task_platform, form).then(function (response) {
        let {message, state, content} = response.data;
        if (state === 200) {
          let {endTime,pipelineId,taskName,telemetryUrl,startTime,flightDistance,flightDuration,videoUrl} = content;
          self.operateForm.pipelineId = pipelineId;
          self.operateForm.taskName = taskName;
          self.operateForm.telemetryUrl = telemetryUrl;
          self.operateForm.startTime = startTime;
          self.operateForm.endTime = endTime;
          self.operateForm.flightDistance = flightDistance;
          self.operateForm.flightDuration = flightDuration;
          self.operateForm.videoUrl = videoUrl;
          self.$Message.success(message);
          self.$Spin.hide();
        }else {
          self.$Message.error(message);
        }
      })
    },
  }
}

</script>

<style scoped>
#content {
  background: #FFFFFF;
  padding: 15px;
  overflow: auto;
  position: relative;
}
#flyTaskMap{
  background: #000;
  border-radius: 5px;
}
.uav-online-select{
  z-index: 888;
  position: relative;
  top: 10px;
  right: -10px;
  width: 888px;
}
.uav-online-select-item{
  height: 24px;
  line-height: 24px;
  color: #FFFFFF;
  background: #0008;
  margin-bottom: 5px;
  border-radius: 5px;
  position: relative;
  cursor: pointer;
}
.uav-item-item{
  font-size: 12px;
  width: 200px;
  padding-right: 5px;
  text-align: left;
}
.uav-item-item>span{
  font-size: 12px;
}
.uav-btn{
  text-align:center;
  font-size: 20px!important;
  position: absolute;
  width: 24px;
  height: 24px;
  background:#0008;
  border-radius: 5px;
}
.item-input {
  height: 45px;
  line-height: 45px;
  margin-bottom: 10px;
}

.item-input-span {
  /*height: inherit;*/
  width: 100px;
}

.item-key {
  /*height: inherit;*/
  width: 150px;
}
.item-value {
  /*height: inherit;*/
  width: 50px;
}

.ivu-form-item-content {
  margin-left: 0 !important;
  position: relative;
  line-height: 32px;
  font-size: 14px;
}

.ivu-form-item {
  margin-bottom: 0;
  width: 100%;
}

.button-item {
  border: #19be6b 1px dashed;
  color: #19be6b;
}

.filter-item {
  margin: 0 5px;
}

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from { transform: rotate(0deg);}
  50%  { transform: rotate(180deg);}
  to   { transform: rotate(360deg);}
}
.demo-spin-col{
  height: 20px;
  position: relative;
}
</style>
